package com.ipay.wechat.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;






import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ipay.core.WechatMessagePacker;
import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.utils.R;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.factory.WechatFactory;
import com.ipay.wechat.service.UserWechatInfoService;
import com.ipay.wechat.util.AddWechatJSUtil;
import com.ipay.wechat.util.SignUtil;

/**
 * 微信和项目对接
 * @author jing
 *
 */
@RestController
public class WechatController {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private static String token = "daoying";
	
	@Autowired
	private Wechat wechat;
	@Autowired
	private UserWechatInfoService uwiService;
	@Autowired
	private JedisExecutor jedies;
	
	
	@RequestMapping("/wechat/valid")
	public void valid(HttpServletRequest request,HttpServletResponse response) throws IOException{
		this.request = request;
		this.response=response;
		String echostr = request.getParameter("echostr");
		logger.info("echostr=="+echostr);
		if(echostr==null || echostr.isEmpty()){    //
			this.responseMsg(this.request, this.response);
		} else{
			if(this.checkSignature(this.request,token)){
				this.print(echostr);
				
			}else{
				this.print("error");
			}
		}
	}
	
	@ResponseBody
	@RequestMapping("/jsGet")
	public R jsGet(@RequestParam String page){
		logger.info("微信支持：" + page);
		page=page.replace("&amp;", "&");
		String ticket=jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TICKET,"ticket");
		logger.info("ticket=="+ticket);
		String json = AddWechatJSUtil.addWeiXinSDK(page,wechat,ticket);
		return R.ok().put("json", json);
	}
	
	private boolean checkSignature(HttpServletRequest request, String token) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String[] tempArray = {token,timestamp,nonce};
		Arrays.sort(tempArray);
		String tempStr = SignUtil.arrayToString(tempArray);
		tempStr = SignUtil.sha1Encode(tempStr);
		if(tempStr.equalsIgnoreCase(signature)){
			return true;
		}else{
			return false;
		}
	}
	private void print(String echostr) {
		try{
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(echostr);
			response.getWriter().flush();
			response.getWriter().close();
		}catch(Exception e){
			e.printStackTrace();

		}
	}
	public void responseMsg(HttpServletRequest request2,
			HttpServletResponse response2) throws IOException {
		// TODO Auto-generated method stub
		//用户发送信息的内容
		String msgType=null;
		//要输出的信息
		WechatMessagePacker packer=new WechatMessagePacker();
		String postStr = null;      //接受信息
		try {
			postStr = readStreamParameter(request.getInputStream());
			logger.info("  postStr=="+postStr);
		} catch (IOException e) {
			e.printStackTrace();
		}  
		//Map集合用来保存信息
		boolean postStrIsNull=true;
		if(postStr==null||"".equals(postStr)){
			postStrIsNull=false;
		}
		logger.info("   postStrIsNull==="+postStrIsNull);
		if(postStrIsNull){  //用户有发送信息才,才能解释
			Map<String, String> map = packer.unpack(postStr);
			if (map==null) {
				return;
			}
			for(Entry<String, String> entry : map.entrySet()){
				if(entry.getKey().equals("MsgType")){
					msgType = entry.getValue();
				}
			}
			WechatFactory wechatFactory=new WechatFactory(response);
			wechatFactory.dealWechatDockingEvents(msgType,map,wechat,uwiService);
			
	}
}

	private String readStreamParameter(ServletInputStream inputStream) {
		// TODO Auto-generated method stub
		StringBuilder buffer = new StringBuilder();
		BufferedReader reader=null;
		try{
			reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
			String line=null;
			while((line = reader.readLine())!=null){
				buffer.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(null!=reader){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		logger.info("buffer.toString()=="+buffer.toString());
		return buffer.toString();
	}
}
